<template>
  <div class="app-container">

    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品种类">
              <el-select v-model="searchObj.ptype" placeholder="产品种类">
                <el-option label="家电" :value="1"></el-option>
                <el-option label="百货" :value="2"></el-option>
                <el-option label="食品" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名字">
              <el-input style="width: 95%" v-model="searchObj.pname" placeholder="产品名字"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="fetchData()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
          <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px;"
    >

      <el-table-column
        label="序号"
        width="70"
        align="center"
      >
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="图片" width="220">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
          <img :src="scope.row.pimage"  alt="产品图片" style="width: 100%; height: 100px;">
          </div>
        </template>

      </el-table-column>
      <el-table-column prop="pname" label="产品名称" width="220"/>
      <el-table-column prop="roleName" label="产品类型" width="220"/>
      <el-table-column prop="pdescription" label="产品介绍" width="250"/>
      <el-table-column label="数量" width="150" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.quantity" size="mini"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeFromCart(scope.row.id)" title="从购物车移除" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />

    <el-row style="margin-top: 20px;">
      <el-col :span="24" style="text-align: right;">
        <el-button type="primary" size="mini" @click="placeOrder">下单</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import api from '@/api/system/sysUserProduct'
import SysProduct from '@/api/system/sysProduct'
import { MessageBox } from 'element-ui';
const defaultForm = {
  fType: '',
  id: '',
  pname: '',
  pimage: '',
  ptype: '',
  roleName: '',
  pdescription: ''

}
export default {
  name: 'shopMall',
  props: ['fType'],
  data() {
    return {

      listLoading: true, // 数据是否正在加载
      list: null, // banner列表
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询表单对象
      createTimes: [],

      dialogVisible: false,
      Product: defaultForm,
      saveBtnDisabled: false,
      dialogRoleVisible: false,
      isIndeterminate: false, // 是否是不确定的
      checkAll: false // 是否全选
    }
  },
  computed: {
    SysProduct() {
      return SysProduct
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    console.log('list created......')
    const fType = this.$route.params.fType;
    console.log(fType)
    this.fType = fType;
    this.fetchData()
  },

  // 生命周期函数：内存准备完毕，页面渲染成功
  mounted() {
    console.log('list mounted......')
  },

  methods: {
    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size)
      this.limit = size
      this.fetchData(1)
    },

    // 加载banner列表数据
    fetchData(page = 1) {
      this.page = page
      console.log('翻页。。。' + this.page)

      api.getPageList(this.page, this.limit,this.fType, this.searchObj).then(
        response => {
          // this.list = response.data.list
          this.list = response.data.records
          this.total = response.data.total
          this.list.forEach(item => {
            this.$set(item, 'quantity', 0);
          });

          // 数据加载并绑定成功
          this.listLoading = false

        }
      )
    },

    // 重置查询表单
    resetData() {
      console.log('重置查询表单')
      this.searchObj = {}
      this.createTimes = []
      this.fetchData()
    },

    fetchDataById(id) {
      api.getById(id).then(response => {
        this.Product = response.data
      })
    },


    // 根据id更新记录
    updateData() {
      api.updateById(this.Product).then(response => {
        this.$message.success(response.message || '操作成功')
        this.dialogVisible = false
        this.fetchData(this.page)
      })
    },

    showAssignRole(row) {
      this.Product = row
      this.dialogRoleVisible = true
      this.getRoles()
    },

    removeFromCart(productId) {
      const index = this.list.findIndex(item => item.id === productId)

      if (index !== -1) {
        // 如果找到商品，则将其数量置为 0
        console.log(this.list[index].quantity)
        this.list[index].quantity = 0
      }


    },

    placeOrder() {
      // 过滤出数量不为 0 的产品
      const nonZeroItems = this.list.filter(item => item.quantity !== 0);

      // 如果购物车为空，给出提示并返回
      if (nonZeroItems.length === 0) {
        MessageBox.alert('购物车为空，无法下单', '提示', {
          confirmButtonText: '确定',
          type: 'info'
        });
        return;
      }

      // 收集非零数量的商品 ID 和数量
      const shoppingVo = {
        ids: nonZeroItems.map(item => item.id),
        count: nonZeroItems.map(item => item.quantity)
      };
      // 模拟向后端发送订单
      api.BuyProduct(shoppingVo).then(response => {

          this.$message.success('购买成功')

          // 发送订单后，清空购物车中数量为 0 的商品
          this.list.forEach(item => {

              item.quantity = 0;

          });
        })
        .catch(error => {
          // 下单失败的处理，可以给出相应的提示或记录错误日志
          console.error('订单发送失败:', error);
        });
    }

  }
}
</script>

